package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao {

    private DataSource dataSource;
    @Autowired
    public DefaultGoodsDao(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public List<Map> findGoods()  {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet =null;
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();
            String sql = "select * from tb_goods";
            resultSet = statement.executeQuery(sql);

            ArrayList<Map> maps = new ArrayList<>();
            ResultSetMetaData metaData = resultSet.getMetaData();
            while (resultSet.next()){
                /*HashMap hashMap = new HashMap();
                for (int i = 1; i < 5 ; i++) {
                    hashMap.put(metaData.getColumnLabel(i), resultSet.getObject(i));
                }
                maps.add(hashMap);*/
                maps.add(rowmap(metaData,resultSet));
            }
            return maps;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        } finally {
            close(resultSet,statement,connection);
        }


    }
    private Map rowmap(ResultSetMetaData metaData,ResultSet resultSet) throws SQLException {
        HashMap hashMap = new HashMap();
        for (int i = 1; i < 5 ; i++) {
            hashMap.put(metaData.getColumnLabel(i), resultSet.getObject(i));
        }

        return hashMap;
    }
    private void close(ResultSet resultSet,Statement statement,Connection connection){
        if (resultSet == null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement == null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection == null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
